<?php

declare (strict_types=1);

namespace App\Models\GameDB\Pet;

use App\Models\MainDB\Gift;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PoolPrize extends Model
{
    protected $connection = 'mysql_game';
    protected $table = 'lottery_pet_pool_prize';
    //protected $fillable = [];
    protected $guarded = [];

    //protected $casts = ['id' => 'int', 'user_id' => 'integer', 'amount' => 'integer', 'balance' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime'];

    public function one(array $filters)
    {
        return self::query()->where($filters)->first();
    }

    public function list(array $filters, $fields = ['*'], $page = 1, $perPage = 20)
    {
        $query = self::query()->where($filters);
        if ($perPage > 0) {
            $res = $query->paginate($perPage, $fields, 'page', $page);
        } else {
            $res = $query->select($fields)->get();
        }
        return $res;
    }

//    public function getGiftInfoList($filters, $fields){
//        $query = self::query()->select($fields)->join(app('model_lottery_pet_gift_template')->getTable(),
//            'gift_template_id', '=', app('model_lottery_pet_gift_template')->getTable() . ".id")
//            ->join(app('model_gift')->getTable(),
//                app('model_gift') . '.gift_id', '=', app('model_lottery_pet_gift_template')->getTable() . ".id")
//        ;
//        return $query->where($filters)->get();
//    }

    public function getPrizeListWithGift(array $filters, array $fields)
    {
        $query = self::query()->select($fields)->join(app('model_lottery_pet_gift_template')->getTable(),
            'gift_template_id', '=', app('model_lottery_pet_gift_template')->getTable() . ".id");
        return $query->where($filters)->get();
    }


    public function listWithGift(array $filters, $fields = ['*'], $page = 1, $perPage = 20)
    {
        $query = self::query()->where($filters);
        if ($perPage > 0) {
            $res = $query->paginate($perPage, $fields, 'page', $page);
        } else {
            $res = $query->select($fields)->get();
        }
        return $res;
    }

    public function updateData(array $filters, array $data)
    {
        return self::query()->where($filters)->update($data);
    }

    public function appendPrizes($poolGroup, Collection $prizeList)
    {
        $insert = [];
        $update = [];

        if (is_array($poolGroup)) {
            $poolId  = $poolGroup['pool_id'];
            $groupId = $poolGroup['group_id'];
            $tag     = $poolGroup['tag'];
        } else {
            $poolId  = $poolGroup->pool_id;
            $groupId = $poolGroup->group_id;
            $tag     =  $poolGroup->tag;
        }

        $pool = self::query()->where(['group_id' => $groupId])->get();
        $pool = array_column($pool->toArray(), NULL, 'gift_template_id');
        foreach ($prizeList as $prize) {
            $prizeId       = $prize->gift_template_id;
            //$templatePrize = $pool->where('gift_template_id', $prizeId)->first();
            if (isset($pool[$prizeId])) { // 奖励存在
                $update[$prizeId] = $prize['count'];
            } else { // 奖励不存在
                $insert[] = ['pool_id' => $poolId, 'group_id' => $groupId, 'gift_template_id' => $prizeId, 'tag' => $tag, 'count' => $prize['count'], 'template_count' => $prize['count']];
            }
        }
        if ($insert) {
            self::query()->insert($insert);
        }
        if ($update) {
            $this->batchIncPrizesByGroup($poolGroup, $update);
        }
    }

    // 批量增加礼物数量（抽完补奖池, 额外设置总数）
    public function batchIncPrizesByGroup($poolGroup, array $update)
    {
        if (empty($update)) {
            return true;
        }

        if (is_array($poolGroup)) {
            $groupId = $poolGroup['group_id'];
        } else {
            $groupId = $poolGroup->group_id;
        }

        $prizeIds      = array_keys($update);
        $prizeIdsSting = implode(',', $prizeIds);

        $table = $this->getTable();
        $sql   = "update {$table} set ";
        // 增加数量
        $sql .= "`count` = case `gift_template_id`";
        foreach ($update as $prizeId => $prizeCount) {
            $sql .= "when {$prizeId} then `count` + {$prizeCount} ";
        }
        $sql .= "else `count` end, ";
        // 增加总数
        $sql .= "`template_count` = case `gift_template_id` ";
        foreach ($update as $prizeId => $prizeCount) {
            $sql .= "when {$prizeId} then `template_count` + {$prizeCount} ";
        }
        $sql .= "else `template_count` end ";
        // 条件
        $sql .= " where group_id = '{$groupId}' and gift_template_id in ($prizeIdsSting)";

//        self::query()->where('group_ids', $groupId)->whereIn('gift_template_id', $prizeIds)->lockForUpdate()->get();
        return DB::connection('mysql_game')->update($sql);
    }


    // 批量减少礼物数量
    public function batchDecPrizesByGroup($poolGroup, array $update)
    {
        if (empty($update)) {
            return true;
        }
        $groupIds    = [];
        $templateIds = [];


        $table = $this->getTable();
        $sql   = "update {$table} set  `count` = case ";
        foreach ($update as $groupId => $groupPrize) {
            $groupIds[] = $groupId;
            foreach ($groupPrize as $prizeId => $prizeCount) {
                $templateIds[] = $prizeId;
                $sql           .= "when group_id = {$groupId} and `gift_template_id` = {$prizeId} then `count` - {$prizeCount} ";
            }
        }
        $groupIdsSting     = implode(',', $groupIds);
        $templateIdsString = implode(',', $templateIds);
        $sql               .= "else `count` end where group_id in ($groupIdsSting) and gift_template_id in ($templateIdsString)";

//        self::query()->whereIn('group_id', $groupIds)->whereIn('gift_template_id', $templateIds)->lockForUpdate()->get();
        $res =  DB::connection('mysql_game')->update($sql);

        return $res;
    }

    public function addLock(array $filters)
    {
        self::query()->where($filters)->lockForUpdate();
    }
}
